package com.example.choupaiapp.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.choupaiapp.R;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ActivityManager;
import com.example.choupaiapp.common.util.GsonUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.OpenIdIsRegistBean;
import com.example.choupaiapp.main.bean.QQLoginBean;
import com.example.choupaiapp.main.bean.QQLoginUserInfoBean;
import com.example.choupaiapp.main.bean.TokenBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.VersionBean;
import com.example.choupaiapp.main.bean.WechatLoginBean;
import com.example.choupaiapp.main.bean.WechatLoginUserInfoBean;
import com.example.choupaiapp.main.bean.WeiboLoginUserInfoBean;
import com.example.choupaiapp.main.callback.WechatCallBack;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.QQLoginUtil;
import com.example.choupaiapp.main.util.WechatLoginUtil;
import com.example.choupaiapp.main.util.WeiboLoginUtil;
import com.example.choupaiapp.main.view.PhoneEditText;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;
import com.umeng.umverify.UMVerifyHelper;
import com.umeng.umverify.listener.UMPreLoginResultListener;
import com.umeng.umverify.listener.UMTokenResultListener;
import com.umeng.umverify.model.UMTokenRet;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by ASUS on 2020/4/21.
 */

public class OtherLoginActivity extends CommonActivity implements WechatCallBack {

    @BindView(R.id.phone_et)
    PhoneEditText phoneEt;
    @BindView(R.id.password_login)
    TextView password_login;
    private String loginFlag = "";
    private BaseUiListener listener;
    private UserInfoListener userInfoListener;
    private SelfWbAuthListener weiboListener;
    /**
     * 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能
     */
    private Oauth2AccessToken mAccessToken;
    private UMVerifyHelper umVerifyHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_login);
    }

    @Override
    protected void initView() {
        UMTokenResultListener umTokenResultListener = new UMTokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.e("s:" + s);
                        UMTokenRet tokenRet = null;
                        try {
                            tokenRet = JSON.parseObject(s, UMTokenRet.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (tokenRet != null && !("600001").equals(tokenRet.getCode())) {
                            String token = tokenRet.getToken();
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("mobile",phoneEt.getPhoneText().toString());
                                jsonObject.put("token", token);
                                jsonObject.put("appkey", Config.UMENG_APP_KEY);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.request(RequestType.POSTJSON, Url.RIGIST_LOGIN, null, jsonObject.toString(), new Callback<TokenBean>() {
                                @Override
                                public void onSuccess(TokenBean tokenBean) {
                                    if (tokenBean.getCode() == Contacts.SUCCESS) {
                                        SharedPreferencesHelp.put("token", tokenBean.getToken());
                                        finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
                                            @Override
                                            public void onSuccess(UserInfoBean userInfoBean) {
                                                if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                                    SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                                                    CrashReport.setUserId(context, userInfoBean.getUser().getMobile());
                                                    if (tokenBean.getFirst() == 1) {
                                                        EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                            @Override
                                                            public void onSuccess() {
                                                                umVerifyHelper.hideLoginLoading();
                                                                dismissDialog();
                                                                EMClient.getInstance().groupManager().loadAllGroups();
                                                                EMClient.getInstance().chatManager().loadAllConversations();
                                                                JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                MobclickAgent.onProfileSignIn("CP_" + userInfoBean.getUser().getUserId());
                                                                Bundle bundle = new Bundle();
                                                                bundle.putInt("flag", 1);
                                                                startFinishActivity(ChangePersonalInfoActivity.class, bundle);
                                                            }

                                                            @Override
                                                            public void onProgress(int progress, String status) {

                                                            }

                                                            @Override
                                                            public void onError(int code, final String message) {
                                                                runOnUiThread(() -> {
                                                                    Logger.e(code + ":" + message);
                                                                    umVerifyHelper.hideLoginLoading();
                                                                    dismissDialog();
                                                                    JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                    MobclickAgent.onProfileSignIn("CP_" + userInfoBean.getUser().getUserId());
                                                                    showImageToas("即时通讯登录失败 私信功能不能使用");
                                                                    Bundle bundle = new Bundle();
                                                                    bundle.putInt("flag", 2);
                                                                    startFinishActivity(ChangePersonalInfoActivity.class, bundle);
                                                                });

                                                            }
                                                        });
                                                    } else {
                                                        EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                            @Override
                                                            public void onSuccess() {
                                                                umVerifyHelper.hideLoginLoading();
                                                                dismissDialog();
                                                                EMClient.getInstance().groupManager().loadAllGroups();
                                                                EMClient.getInstance().chatManager().loadAllConversations();
                                                                JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                MobclickAgent.onProfileSignIn("CP_" + userInfoBean.getUser().getUserId());
                                                                ActivityManager.getActivityManager().popAllActivity();
                                                                startFinishActivity(MainActivity.class);
                                                            }

                                                            @Override
                                                            public void onProgress(int progress, String status) {

                                                            }

                                                            @Override
                                                            public void onError(int code, final String message) {
                                                                runOnUiThread(() -> {
                                                                    Logger.e(code + ":" + message);
                                                                    umVerifyHelper.hideLoginLoading();
                                                                    dismissDialog();
                                                                    JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                    MobclickAgent.onProfileSignIn("CP_" + userInfoBean.getUser().getUserId());
                                                                    showImageToas("即时通讯登录失败 私信功能不能使用");
                                                                    ActivityManager.getActivityManager().popAllActivity();
                                                                    startFinishActivity(MainActivity.class);
                                                                });

                                                            }
                                                        });
                                                    }
                                                } else {
                                                    umVerifyHelper.hideLoginLoading();
                                                    dismissDialog();
                                                    if (userInfoBean.getCode() == Contacts.TOKEN_EMPTY) {
                                                    } else {
                                                        showImageToas(userInfoBean.getMsg());
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onError(Response<String> response) {
                                                super.onError(response);
                                                dismissDialog();
                                                umVerifyHelper.hideLoginLoading();
                                            }
                                        });
                                    } else {
                                        umVerifyHelper.hideLoginLoading();
                                        dismissDialog();
                                        if (tokenBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(tokenBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                    umVerifyHelper.hideLoginLoading();
                                }
                            });
                        }
                    }
                });

            }

            @Override
            public void onTokenFailed(String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        umVerifyHelper.hideLoginLoading();
                    }
                });
            }
        };
        umVerifyHelper = UMVerifyHelper.getInstance(this, umTokenResultListener);
        umVerifyHelper.setAuthSDKInfo(Config.UMENG_SCECET_KEY);
        umVerifyHelper.setAuthListener(umTokenResultListener);
        umVerifyHelper.setLoggerEnable(true);
        umVerifyHelper.accelerateLoginPage(5000, new UMPreLoginResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.e("预取号成功:" + s);
                    }
                });
            }

            @Override
            public void onTokenFailed(String s, String s1) {

            }
        });
    }

    @Override
    protected void initData() {
        finalOkGo.request(RequestType.POST, Url.APP_VERSION_UPDATE, null, Url.APP_VERSION_UPDATE, new Callback<VersionBean>() {
            @Override
            public void onSuccess(VersionBean versionBean) {
                if (versionBean.getCode() == Contacts.SUCCESS) {
                    if (versionBean.getVersions().getAndroidIsShow() == 1) {
                        password_login.setVisibility(View.VISIBLE);
                    } else {
                        password_login.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @OnClick({R.id.wechat_login, R.id.qq_login, R.id.sina_login, R.id.next, R.id.password_login})
    public void onViewClicked(View view) {
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.next:
                if (phoneEt.getPhoneText().startsWith("1")) {
                    if (phoneEt.getPhoneText().length() == 11) {
                        boolean check = umVerifyHelper.checkEnvAvailable();
                        if (check) {
                            umVerifyHelper.getVerifyToken(5000);
                        } else {
                            showImageToas("请打开您的4g网络");
                        }
                    } else {
                        showImageToas("请输入正确的手机号");
                    }
                } else {
                    showImageToas("请输入正确的手机号");
                }
                break;
            case R.id.wechat_login:
                if (WechatLoginUtil.getInstance().isWeChatAppInstalled()) {
                    showDialog(this, "登录中...");
                    loginFlag = "wechat";
                    if (!TextUtils.isEmpty((String) SharedPreferencesHelp.get("weChat_token", ""))) {
                        finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Config.WEIXIN_APP_ID
                                        + "&grant_type=refresh_token&refresh_token=" + SharedPreferencesHelp.get("weChat_token", ""),
                                null, "refresh_token",
                                new Callback<WechatLoginBean>() {
                                    @Override
                                    public void onSuccess(WechatLoginBean refresh) {
                                        if (refresh != null && refresh.getOpenid() != null && !TextUtils.isEmpty(refresh.getOpenid())) {
                                            SharedPreferencesHelp.put("weChat_token", refresh.getRefresh_token());
                                            HttpParams params = new HttpParams();
                                            params.put("wechatOpenid", refresh.getOpenid());
//                                            if (!TextUtils.isEmpty(ExampleUtil.getImei(context, ""))) {
//                                                params.put("deviceCode", ExampleUtil.getImei(context, ""));
//                                            } else {
//                                                if (!TextUtils.isEmpty(JPushInterface.getUdid(context))) {
//                                                    params.put("deviceCode", JPushInterface.getUdid(context));
//                                                } else {
//                                                    if (!TextUtils.isEmpty(JPushInterface.getRegistrationID(context))) {
//                                                        params.put("deviceCode", JPushInterface.getRegistrationID(context));
//                                                    } else {
//                                                        params.put("deviceCode", System.currentTimeMillis() + "");
//                                                    }
//                                                }
//                                            }
                                            finalOkGo.request(RequestType.POST, Url.OPEN_ID_IS_RIGIST, params, Url.OPEN_ID_IS_RIGIST, new Callback<OpenIdIsRegistBean>() {
                                                @Override
                                                public void onSuccess(OpenIdIsRegistBean openIdIsRegistBean) {
                                                    if (openIdIsRegistBean.getCode() == Contacts.SUCCESS) {
                                                        if (openIdIsRegistBean.getVerify() == 0) {
                                                            finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/userinfo?access_token="
                                                                            + refresh.getAccess_token()
                                                                            + "&openid=" + refresh.getOpenid(),
                                                                    null, "wechatInfo", new Callback<WechatLoginUserInfoBean>() {
                                                                        @Override
                                                                        public void onSuccess(WechatLoginUserInfoBean wechatLoginUserInfoBean) {
                                                                            if (wechatLoginUserInfoBean.getErrcode() != 40003) {
                                                                                dismissDialog();
                                                                                Bundle bundle = new Bundle();
                                                                                bundle.putString("headUrl", wechatLoginUserInfoBean.getHeadimgurl());
                                                                                bundle.putString("name", wechatLoginUserInfoBean.getNickname());
                                                                                bundle.putString("sex", wechatLoginUserInfoBean.getSex() + "");
                                                                                bundle.putString("openId", wechatLoginUserInfoBean.getOpenid());
                                                                                bundle.putString("flag", "wechat");
                                                                                startActivity(BindPhoneActivity.class, bundle);
                                                                            } else {
                                                                                dismissDialog();
                                                                                showImageToas("获取用户信息失败");
                                                                            }
                                                                        }

                                                                        @Override
                                                                        public void onError(Response<String> response) {
                                                                            super.onError(response);
                                                                            dismissDialog();
                                                                        }
                                                                    });

                                                        } else {
                                                            SharedPreferencesHelp.put("token", openIdIsRegistBean.getToken());
                                                            finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
                                                                @Override
                                                                public void onSuccess(UserInfoBean userInfoBean) {
                                                                    if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                                                        SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                                                                        CrashReport.setUserId(context, userInfoBean.getUser().getMobile());
                                                                        EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                                            @Override
                                                                            public void onSuccess() {
                                                                                dismissDialog();
                                                                                EMClient.getInstance().groupManager().loadAllGroups();
                                                                                EMClient.getInstance().chatManager().loadAllConversations();
                                                                                JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                                MobclickAgent.onProfileSignIn("Wechat", "CP_" + userInfoBean.getUser().getUserId());
                                                                                ActivityManager.getActivityManager().popAllActivity();
                                                                                startFinishActivity(MainActivity.class);
                                                                            }

                                                                            @Override
                                                                            public void onProgress(int progress, String status) {

                                                                            }

                                                                            @Override
                                                                            public void onError(int code, final String message) {
                                                                                runOnUiThread(() -> {
                                                                                    dismissDialog();
                                                                                    JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                                    MobclickAgent.onProfileSignIn("Wechat", "CP_" + userInfoBean.getUser().getUserId());
                                                                                    showImageToas("即时通讯登录失败 私信功能不能使用");
                                                                                    ActivityManager.getActivityManager().popAllActivity();
                                                                                    startFinishActivity(MainActivity.class);
                                                                                });

                                                                            }
                                                                        });
                                                                    } else {
                                                                        dismissDialog();
                                                                        showImageToas(userInfoBean.getMsg());
                                                                    }
                                                                }

                                                                @Override
                                                                public void onError(Response<String> response) {
                                                                    super.onError(response);
                                                                    dismissDialog();
                                                                }
                                                            });
                                                        }
                                                    } else {
                                                        dismissDialog();
                                                        showImageToas(openIdIsRegistBean.getMsg());
                                                    }
                                                }

                                                @Override
                                                public void onError(Response<String> response) {
                                                    super.onError(response);
                                                    dismissDialog();
                                                }
                                            });
                                        } else {
                                            WechatLoginUtil.getInstance().setWechatCallBack(OtherLoginActivity.this);
                                            WechatLoginUtil.getInstance().wechatLogin();
                                        }
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        dismissDialog();
                                    }
                                });
                    } else {
                        WechatLoginUtil.getInstance().setWechatCallBack(this);
                        WechatLoginUtil.getInstance().wechatLogin();
                    }
                } else {
                    showImageToas("请先安装微信客户端");
                }
                break;
            case R.id.qq_login:
                if (QQLoginUtil.getInstance().isQQAppInstalled()) {
                    showDialog(this, "登录中...");
                    loginFlag = "qq";
                    listener = new BaseUiListener();
                    userInfoListener = new UserInfoListener();
                    QQLoginUtil.getInstance().qqLogin(this, listener);
                } else {
                    showImageToas("请先安装qq客户端");
                }
                break;
            case R.id.sina_login:
                showDialog(this, "登录中...");
                loginFlag = "weibo";
                weiboListener = new SelfWbAuthListener();
                WeiboLoginUtil.getInstance().weiboLogin(this, weiboListener);
                break;
            case R.id.password_login:
                EventBus.getDefault().postSticky("agree_agreedment");
                startActivity(PasswordLoginActivity.class);
                break;
        }
    }

    @Override
    public void callBack(BaseResp baseResp) {
        String result = "";
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Logger.e("sssssssssss");
                SendAuth.Resp newResp = (SendAuth.Resp) baseResp;
                finalOkGo.request(RequestType.GET,
                        "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Config.WEIXIN_APP_ID
                                + "&secret=" + Config.WEIXIN_APP_SCRECT + "&code=" + newResp.code
                                + "&grant_type=authorization_code", null, "wechatLogin", new Callback<WechatLoginBean>() {
                            @Override
                            public void onSuccess(WechatLoginBean wechatLoginBean) {
                                if (wechatLoginBean != null && wechatLoginBean.getOpenid() != null && !TextUtils.isEmpty(wechatLoginBean.getOpenid())) {
                                    finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Config.WEIXIN_APP_ID
                                                    + "&grant_type=refresh_token&refresh_token=" + wechatLoginBean.getRefresh_token(), null, "refresh_token",
                                            new Callback<WechatLoginBean>() {
                                                @Override
                                                public void onSuccess(WechatLoginBean refresh) {
                                                    if (refresh != null && refresh.getOpenid() != null && !TextUtils.isEmpty(refresh.getOpenid())) {
                                                        SharedPreferencesHelp.put("weChat_token", refresh.getRefresh_token());
                                                        HttpParams params = new HttpParams();
                                                        params.put("wechatOpenid", refresh.getOpenid());
//                                                        if (!TextUtils.isEmpty(ExampleUtil.getImei(context, ""))) {
//                                                            params.put("deviceCode", ExampleUtil.getImei(context, ""));
//                                                        } else {
//                                                            if (!TextUtils.isEmpty(JPushInterface.getUdid(context))) {
//                                                                params.put("deviceCode", JPushInterface.getUdid(context));
//                                                            } else {
//                                                                if (!TextUtils.isEmpty(JPushInterface.getRegistrationID(context))) {
//                                                                    params.put("deviceCode", JPushInterface.getRegistrationID(context));
//                                                                } else {
//                                                                    params.put("deviceCode", System.currentTimeMillis() + "");
//                                                                }
//                                                            }
//                                                        }
                                                        finalOkGo.request(RequestType.POST, Url.OPEN_ID_IS_RIGIST, params, Url.OPEN_ID_IS_RIGIST, new Callback<OpenIdIsRegistBean>() {
                                                            @Override
                                                            public void onSuccess(OpenIdIsRegistBean openIdIsRegistBean) {
                                                                if (openIdIsRegistBean.getCode() == Contacts.SUCCESS) {
                                                                    if (openIdIsRegistBean.getVerify() == 0) {
                                                                        finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/userinfo?access_token="
                                                                                        + refresh.getAccess_token()
                                                                                        + "&openid=" + refresh.getOpenid(),
                                                                                null, "wechatInfo", new Callback<WechatLoginUserInfoBean>() {
                                                                                    @Override
                                                                                    public void onSuccess(WechatLoginUserInfoBean wechatLoginUserInfoBean) {
                                                                                        if (wechatLoginUserInfoBean.getErrcode() != 40003) {
                                                                                            dismissDialog();
                                                                                            Bundle bundle = new Bundle();
                                                                                            bundle.putString("headUrl", wechatLoginUserInfoBean.getHeadimgurl());
                                                                                            bundle.putString("name", wechatLoginUserInfoBean.getNickname());
                                                                                            bundle.putString("sex", wechatLoginUserInfoBean.getSex() + "");
                                                                                            bundle.putString("openId", wechatLoginUserInfoBean.getOpenid());
                                                                                            bundle.putString("flag", "wechat");
                                                                                            startActivity(BindPhoneActivity.class, bundle);
                                                                                        } else {
                                                                                            dismissDialog();
                                                                                            showImageToas("获取用户信息失败");
                                                                                        }
                                                                                    }

                                                                                    @Override
                                                                                    public void onError(Response<String> response) {
                                                                                        super.onError(response);
                                                                                        dismissDialog();
                                                                                    }
                                                                                });

                                                                    } else {
                                                                        SharedPreferencesHelp.put("token", openIdIsRegistBean.getToken());
                                                                        finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
                                                                            @Override
                                                                            public void onSuccess(UserInfoBean userInfoBean) {
                                                                                if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                                                                    SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                                                                                    CrashReport.setUserId(context, userInfoBean.getUser().getMobile());
                                                                                    EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                                                        @Override
                                                                                        public void onSuccess() {
                                                                                            dismissDialog();
                                                                                            EMClient.getInstance().groupManager().loadAllGroups();
                                                                                            EMClient.getInstance().chatManager().loadAllConversations();
                                                                                            JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                                            MobclickAgent.onProfileSignIn("Wechat", "CP_" + userInfoBean.getUser().getUserId());
                                                                                            ActivityManager.getActivityManager().popAllActivity();
                                                                                            startFinishActivity(MainActivity.class);
                                                                                        }

                                                                                        @Override
                                                                                        public void onProgress(int progress, String status) {

                                                                                        }

                                                                                        @Override
                                                                                        public void onError(int code, final String message) {
                                                                                            runOnUiThread(() -> {
                                                                                                dismissDialog();
                                                                                                JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                                                MobclickAgent.onProfileSignIn("Wechat", "CP_" + userInfoBean.getUser().getUserId());
                                                                                                showImageToas("即时通讯登录失败 私信功能不能使用");
                                                                                                ActivityManager.getActivityManager().popAllActivity();
                                                                                                startFinishActivity(MainActivity.class);
                                                                                            });

                                                                                        }
                                                                                    });
                                                                                } else {
                                                                                    dismissDialog();
                                                                                    showImageToas(userInfoBean.getMsg());
                                                                                }
                                                                            }

                                                                            @Override
                                                                            public void onError(Response<String> response) {
                                                                                super.onError(response);
                                                                                dismissDialog();
                                                                            }
                                                                        });
                                                                    }
                                                                } else {
                                                                    dismissDialog();
                                                                    showImageToas(openIdIsRegistBean.getMsg());
                                                                }
                                                            }

                                                            @Override
                                                            public void onError(Response<String> response) {
                                                                super.onError(response);
                                                                dismissDialog();
                                                            }
                                                        });
                                                    } else {
                                                        dismissDialog();
                                                        showImageToas("获取用户信息失败");
                                                    }
                                                }

                                                @Override
                                                public void onError(Response<String> response) {
                                                    super.onError(response);
                                                    dismissDialog();
                                                }
                                            });

                                } else {
                                    dismissDialog();
                                    showImageToas("获取用户信息失败");
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                dismissDialog();
                result = "发送取消";
                showImageToas(result);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                dismissDialog();
                result = "发送被拒绝";
                showImageToas(result);
                break;
            default:
                dismissDialog();
                result = "发送返回";
                showImageToas(result);
                break;
        }
    }

    private class SelfWbAuthListener implements com.sina.weibo.sdk.auth.WbAuthListener {
        @Override
        public void onSuccess(final Oauth2AccessToken token) {
            runOnUiThread(() -> {
                mAccessToken = token;
                if (mAccessToken.isSessionValid()) {
                    finalOkGo.request(RequestType.GET, Config.WEIBO_URL + "?access_token=" + mAccessToken.getToken() + "&&uid=" + mAccessToken.getUid(),
                            null, Config.WEIBO_URL, new Callback<WeiboLoginUserInfoBean>() {
                                @Override
                                public void onSuccess(WeiboLoginUserInfoBean weiboLoginUserInfoBean) {
                                    if (weiboLoginUserInfoBean.getError() != null && !TextUtils.isEmpty(weiboLoginUserInfoBean.getError())) {
                                        showImageToas("获取个人信息失败");
                                        dismissDialog();
                                    } else {
                                        HttpParams params = new HttpParams();
                                        params.put("sinaOpenid", mAccessToken.getUid());
//                                        if (!TextUtils.isEmpty(ExampleUtil.getImei(context, ""))) {
//                                            params.put("deviceCode", ExampleUtil.getImei(context, ""));
//                                        } else {
//                                            if (!TextUtils.isEmpty(JPushInterface.getUdid(context))) {
//                                                params.put("deviceCode", JPushInterface.getUdid(context));
//                                            } else {
//                                                if (!TextUtils.isEmpty(JPushInterface.getRegistrationID(context))) {
//                                                    params.put("deviceCode", JPushInterface.getRegistrationID(context));
//                                                } else {
//                                                    params.put("deviceCode", System.currentTimeMillis() + "");
//                                                }
//                                            }
//                                        }
                                        finalOkGo.request(RequestType.POST, Url.OPEN_ID_IS_RIGIST, params, Url.OPEN_ID_IS_RIGIST, new Callback<OpenIdIsRegistBean>() {
                                            @Override
                                            public void onSuccess(OpenIdIsRegistBean openIdIsRegistBean) {
                                                if (openIdIsRegistBean.getCode() == Contacts.SUCCESS) {

                                                    if (openIdIsRegistBean.getVerify() == 0) {
                                                        dismissDialog();
                                                        Bundle bundle = new Bundle();
                                                        bundle.putString("headUrl", weiboLoginUserInfoBean.getAvatar_hd());
                                                        bundle.putString("name", weiboLoginUserInfoBean.getName());
                                                        if (!TextUtils.isEmpty(weiboLoginUserInfoBean.getGender())) {
                                                            if (weiboLoginUserInfoBean.getGender().equals("m")) {
                                                                bundle.putString("sex", "1");
                                                            } else {
                                                                bundle.putString("sex", "2");
                                                            }
                                                        } else {
                                                            bundle.putString("sex", "0");
                                                        }
                                                        bundle.putString("openId", mAccessToken.getUid());
                                                        bundle.putString("flag", "weibo");
                                                        startActivity(BindPhoneActivity.class, bundle);
                                                    } else {
                                                        SharedPreferencesHelp.put("token", openIdIsRegistBean.getToken());
                                                        finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
                                                            @Override
                                                            public void onSuccess(UserInfoBean userInfoBean) {
                                                                if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                                                    SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                                                                    EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                                        @Override
                                                                        public void onSuccess() {
                                                                            dismissDialog();
                                                                            EMClient.getInstance().groupManager().loadAllGroups();
                                                                            EMClient.getInstance().chatManager().loadAllConversations();
                                                                            JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                            MobclickAgent.onProfileSignIn("Sina", "CP_" + userInfoBean.getUser().getUserId());
                                                                            ActivityManager.getActivityManager().popAllActivity();
                                                                            startFinishActivity(MainActivity.class);
                                                                        }

                                                                        @Override
                                                                        public void onProgress(int progress, String status) {

                                                                        }

                                                                        @Override
                                                                        public void onError(int code, final String message) {
                                                                            runOnUiThread(() -> {
                                                                                dismissDialog();
                                                                                JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                                                MobclickAgent.onProfileSignIn("Sina", "CP_" + userInfoBean.getUser().getUserId());
                                                                                showImageToas("即时通讯登录失败 私信功能不能使用");
                                                                                ActivityManager.getActivityManager().popAllActivity();
                                                                                startFinishActivity(MainActivity.class);
                                                                            });

                                                                        }
                                                                    });
                                                                } else {
                                                                    dismissDialog();
                                                                    showImageToas(userInfoBean.getMsg());
                                                                }
                                                            }

                                                            @Override
                                                            public void onError(Response<String> response) {
                                                                super.onError(response);
                                                                dismissDialog();
                                                            }
                                                        });
                                                    }
                                                } else {
                                                    dismissDialog();
                                                    showImageToas(openIdIsRegistBean.getMsg());
                                                }
                                            }

                                            @Override
                                            public void onError(Response<String> response) {
                                                super.onError(response);
                                                dismissDialog();
                                            }
                                        });
                                    }

                                }
                            });
                }
            });
        }

        @Override
        public void cancel() {
            showImageToas("取消登录");
        }

        @Override
        public void onFailure(WbConnectErrorMessage errorMessage) {
            showImageToas("登录失败");
            Logger.e(errorMessage.getErrorCode() + "---" + errorMessage.getErrorMessage());
        }
    }

    private class UserInfoListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            Logger.e(o.toString());

            QQLoginUserInfoBean qqLoginUserInfoBean = GsonUtil.jsonStringToClassWithGson(o.toString(), QQLoginUserInfoBean.class);
            dismissDialog();
            if (qqLoginUserInfoBean.getRet() == 0) {
                Bundle bundle = new Bundle();
                bundle.putString("headUrl", qqLoginUserInfoBean.getFigureurl_2());
                bundle.putString("name", qqLoginUserInfoBean.getNickname());
                if (!TextUtils.isEmpty(qqLoginUserInfoBean.getGender())) {
                    if (qqLoginUserInfoBean.getGender().equals("男")) {
                        bundle.putString("sex", "1");
                    } else {
                        bundle.putString("sex", "2");
                    }
                } else {
                    bundle.putString("sex", "0");
                }
                bundle.putString("openId", QQLoginUtil.getInstance().mTencent.getOpenId());
                bundle.putString("flag", "qq");
                startActivity(BindPhoneActivity.class, bundle);
            } else {
                showImageToas("获取个人信息失败");
            }

        }

        @Override
        public void onError(UiError uiError) {

        }

        @Override
        public void onCancel() {

        }
    }


    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object value) {

            Logger.e(value.toString());

            QQLoginBean qqLoginBean = GsonUtil.jsonStringToClassWithGson(value.toString(), QQLoginBean.class);

            if (qqLoginBean.getRet() == 0) {

                HttpParams params = new HttpParams();
                params.put("qqOpenid", qqLoginBean.getOpenid());
//                if (!TextUtils.isEmpty(ExampleUtil.getImei(context, ""))) {
//                    params.put("deviceCode", ExampleUtil.getImei(context, ""));
//                } else {
//                    if (!TextUtils.isEmpty(JPushInterface.getUdid(context))) {
//                        params.put("deviceCode", JPushInterface.getUdid(context));
//                    } else {
//                        if (!TextUtils.isEmpty(JPushInterface.getRegistrationID(context))) {
//                            params.put("deviceCode", JPushInterface.getRegistrationID(context));
//                        } else {
//                            params.put("deviceCode", System.currentTimeMillis() + "");
//                        }
//                    }
//                }
                finalOkGo.request(RequestType.POST, Url.OPEN_ID_IS_RIGIST, params, Url.OPEN_ID_IS_RIGIST, new Callback<OpenIdIsRegistBean>() {
                    @Override
                    public void onSuccess(OpenIdIsRegistBean openIdIsRegistBean) {
                        if (openIdIsRegistBean.getCode() == Contacts.SUCCESS) {
                            if (openIdIsRegistBean.getVerify() == 0) {
                                QQLoginUtil.getInstance().mTencent.setOpenId(qqLoginBean.getOpenid());
                                QQLoginUtil.getInstance().mTencent.setAccessToken(qqLoginBean.getAccess_token(), qqLoginBean.getExpires_in());
                                UserInfo info = new UserInfo(context, QQLoginUtil.getInstance().mTencent.getQQToken());
                                info.getUserInfo(userInfoListener);
                            } else {
                                SharedPreferencesHelp.put("token", openIdIsRegistBean.getToken());
                                finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
                                    @Override
                                    public void onSuccess(UserInfoBean userInfoBean) {
                                        if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                            SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                                            CrashReport.setUserId(context, userInfoBean.getUser().getMobile());
                                            EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                @Override
                                                public void onSuccess() {
                                                    dismissDialog();
                                                    EMClient.getInstance().groupManager().loadAllGroups();
                                                    EMClient.getInstance().chatManager().loadAllConversations();
                                                    JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                    MobclickAgent.onProfileSignIn("QQ", "CP_" + userInfoBean.getUser().getUserId());
                                                    ActivityManager.getActivityManager().popAllActivity();
                                                    startFinishActivity(MainActivity.class);
                                                }

                                                @Override
                                                public void onProgress(int progress, String status) {

                                                }

                                                @Override
                                                public void onError(int code, final String message) {
                                                    runOnUiThread(() -> {
                                                        dismissDialog();
                                                        JPushInterface.setAlias(context, 0, "CP_" + userInfoBean.getUser().getUserId());
                                                        MobclickAgent.onProfileSignIn("QQ", "CP_" + userInfoBean.getUser().getUserId());
                                                        showImageToas("即时通讯登录失败 私信功能不能使用");
                                                        ActivityManager.getActivityManager().popAllActivity();
                                                        startFinishActivity(MainActivity.class);
                                                    });

                                                }
                                            });
                                        } else {
                                            dismissDialog();
                                            showImageToas(userInfoBean.getMsg());
                                        }
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        dismissDialog();
                                    }
                                });
                            }
                        } else {
                            dismissDialog();
                            showImageToas(openIdIsRegistBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });

            } else {
                dismissDialog();
                showImageToas("登录失败");
            }


        }

        @Override
        public void onError(UiError uiError) {
            showImageToas("登录失败");
        }

        @Override
        public void onCancel() {
            showImageToas("取消登录");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (loginFlag.equals("")) {
            super.onActivityResult(requestCode, resultCode, data);
        } else if (loginFlag.equals("weibo")) {
            if (WeiboLoginUtil.mSsoHandler != null) {
                WeiboLoginUtil.mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        } else if (loginFlag.equals("qq")) {
            if (requestCode == Constants.REQUEST_LOGIN ||
                    requestCode == Constants.REQUEST_APPBAR) {
                Tencent.onActivityResultData(requestCode, resultCode, data, listener);
            }
        }

    }
}
